import os.path
import urllib.request
from lxml import etree
def create_request(page):
    url=""
    headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
    }

    if page==1:
        # url="https://sc.chinaz.com/tupian/meinvtupian.html"
        url="https://sc.chinaz.com/psd/"
    else:
        # url="https://sc.chinaz.com/tupian/meinvtupian_{}.html".format(page)
        url="https://sc.chinaz.com/tupian/index_{}.html".format(page)
    print("remote url:%s\t" % url,end='')
    request=urllib.request.Request(url=url,headers=headers)

    return request

def get_content(request):
    response=urllib.request.urlopen(request)
    content=response.read().decode("utf-8")
    return content

def download(content,page):

    tree=etree.HTML(content)
    srclist=tree.xpath("//div[@class='container']//div/img/@data-original")
    namelist=tree.xpath("//div[@class='container']//div/img/@alt")
    path=f"zhanzhangzhijia\\page_{page}"
    if not os.path.exists(path):
        os.makedirs(path)

    for cur in range(len(srclist)):

        filename="{}\\{}.jpg".format(path,namelist[cur])
        absname=os.path.abspath(filename)
        print(f"local path:{absname}")
        urllib.request.urlretrieve("https:{}".format(srclist[cur]),absname)
        # with open(filename,mode='w',encoding="utf-8") as fs:
        #     fs.write(content)
        #     print(f"local path:{os.path.abspath(filename)}")
    # for src in srclist:
    #     print(src)
    # for name in namelist:
    #     print(name)




if __name__ == '__main__':
    start_page=int(input("请输入起始页码:"))
    end_page=int(input("请输出结束页码:"))

    for page in range(start_page,end_page+1):
        request=create_request(page)
        content=get_content(request)
        download(content,page)